var errorLogger = require("pomelo-logger").getLogger("error-log");
module.exports = function(roomId,roomType,max_player,channelService,GameRemote) {
  var playerBasic = require("./playerBasic.js")
  var gameCfg = require("./gameCfg.json")
	//初始化属性
	this.roomId = roomId		                                                         //房间号
	this.roomType = roomType 	                                                       //游戏类型
	this.max_player = max_player                                                     //最大玩家人数
  this.handle = {}                                                                 //玩家操作
  this.beginFlag = false                                                           //游戏开始状态
  this.beginMode = gameCfg.BEGIN_MODE.ALL_READY                                    //ALL_READY  满人且全部人准备后开始   COUNT_DOWN  满人后倒计时开始
  this.min_player = max_player                                                     //最小可开始人数
  this.createTime = (new Date()).getTime()                                         //房间创建时间
  this.beginTimer = 0                                                              //房间开始计时器
  this.countDownTime = 15000                                                       //倒计时结束时间
  this.GameRemote = GameRemote
  this.countDownEndTime = 0
  //创建channel
  channelService.destroyChannel(roomId)
  this.channel = channelService.getChannel(roomId,true)
  //初始化玩家列表
	this.players = []
  //机器人映射表
  this.robots = {}
  this.chairMap = {}

  for(var i = 0;i < this.max_player;i++){
    this.players[i] = new playerBasic(i,this.channel)
  }
  //游戏开始
  this.beginFun = function() {
    this.beginFlag = true
    clearTimeout(this.beginTimer)
    this.gameBegin()
  }
  //游戏开始回调
  this.gameBegin = function() {
    console.log("gameBegin")
  }
  //游戏结算
  this.gameSettlement = function() {
    this.beginFlag = false
    for(var i in this.players){
      if(this.players[i].isActive){
        this.players[i].isReady = false
      }
    }
    this.checkCountDown()
    this.checkPlayer()

  }
   //若房间中没有玩家则关闭
  this.checkPlayer = function() {
    for(var i = 0;i < this.players.length;i++){
      if(this.players[i].isActive && this.players[i].uid > 10000){
        return
      }
    }
    this.gameOver()
  }
	//游戏结束
	this.gameOver = function(info) {
    console.log("gameOver")
    clearTimeout(this.beginTimer)
    var notify = {
      cmd: "gameOver"
    }
    this.sendAll(notify)
    var players = []
    for(var i in this.players){
      if(this.players[i].isActive){
        players.push(this.players[i].uid)
      }
    }
    for(var i in this.robots){
      this.robots[i].destroy()
      delete this.robots[i]
    }
    // console.log("players : ")
    // console.log(players)
    // console.log("this.roomId : "+this.roomId)
    // console.log(this)
    GameRemote.gameOver(this.roomId,players,info)
    channelService.destroyChannel(this.roomId)
	}
  //获取游戏内玩家信息
  this.getPlayersInfo = function() {
    var players = []
    for(var i in this.players){
      players.push(this.players[i].getInfo())
    }
    return players
  }
	//玩家加入
	this.userJoin = function(uid,sid,playerInfo,cb) {
    console.log("userJoin : "+uid)
    //不可重复加入
    for(var i = 0;i < this.max_player;i++){
      if(this.players[i].uid === uid){
        errorLogger.info("userJoin:"+uid+":已在座位上")
        for(var i in this.players){
          errorLogger.info(this.players[i].uid)
        }
        cb(false,"已在座位上")
        return
      }
    }
    //查找空闲位置
    var chair = -1
    for(var i = 0;i < this.max_player;i++){
      if(this.players[i].isActive === false){
        chair = i
        break
      }
    }
    if(chair == -1 || !this.players[chair]){
      errorLogger.info("房间已满 : "+uid)
      cb(false,"房间已满")
      return
    }
    //初始化玩家
    this.chairMap[uid] = chair
    this.players[chair].init(uid,playerInfo)
    var notify = {
      cmd: "userJoin",
      uid: uid,
      chair : chair,
      player : this.players[chair].getInfo()
    }
    this.sendAll(notify)
    cb(true)
    this.checkCountDown()
    //机器人判断
    if(parseInt(uid) > 10000){
      //加入聊天室
      if(!this.channel.getMember(uid)){
        this.channel.add(uid,sid)
      }
    }else{
      this.players[chair].isRobot = true
      var robotBasic = require("../robot/"+this.roomType+"Robot.js")
      this.robots[this.players[chair].uid] = new robotBasic(this.players[chair].uid,this)
    }
    this.joinLaterFun(chair)
	}
  //加入后方法
  this.joinLaterFun = function(chair) {
  }
	//玩家退出
	this.userQuit = function(uid,cb) {
    console.log("userQuit : "+uid)
    uid = ""+uid
    var chair = this.chairMap[uid]
		if(chair == undefined){
      if(cb){
        cb(false,"不在座位上")
      }
      return
    }
    if(this.beginFlag){
      if(cb){
        cb(false,"游戏结束后才能退出")
      }
      return
    }
    if(this.beginMode == gameCfg.BEGIN_MODE.AUTO_READY){
      if(cb){
        cb(false,"不能手动退出")
      }
      return
    }
    var notify = {
      cmd: "userQuit",
      uid: uid,
      chair : chair
    }
    this.sendAll(notify)
    if(this.channel.getMember(uid)){
      var tsid =  this.channel.getMember(uid)['sid']
      if(tsid){
        this.channel.leave(uid,tsid)
      }
    }
    //清除玩家
    this.players[chair].reset()
    delete this.chairMap[uid]
    //重新判断开始倒计时
    this.checkCountDown()
    GameRemote.userQuit(uid,this.roomId)
    if(cb){
      cb(true)
    }
    this.checkPlayer()
	}
  this.handle.userQuit = function(uid,sid,param,cb) {
    this.userQuitBefore(uid,cb)
  }
  this.userQuitBefore = function(uid,cb) {
    this.userQuit(uid,cb)
  }
  //玩家掉线
  this.disconnect = function(uid) {
    console.log("disconnect : "+uid)
    var chair = this.chairMap[uid]
    if(chair == undefined){
      console.log("不在座位上")
      return
    }
    //设为离线状态
    if(this.players[chair].isOnline){
      this.players[chair].isOnline = false
      if(this.channel.getMember(uid)){
        var tsid =  this.channel.getMember(uid)['sid']
        if(tsid){
          this.channel.leave(uid,tsid)
        }
      }
      var notify = {
        cmd: "userDisconne",
        uid: uid,
        chair : chair
      }
      this.sendAll(notify)
    }
    this.disconnectFun(uid)
  }
  this.disconnectFun = function(uid) {
  }
	//玩家重连
	this.reconnection = function(uid,sid) {
    console.log("reconnection : "+uid)
    var chair = this.chairMap[uid]
    if(chair == undefined){
      console.log("不在座位上")
      return
    }
    this.players[chair].isOnline = true
    var notify = {
      cmd: "userReconnection",
      uid: uid,
      chair : chair
    }
    this.sendAll(notify)
    if(!this.channel.getMember(uid)){
      this.channel.add(uid,sid)
    }
    this.reconnectionFun(uid)
	}
  this.reconnectionFun = function(uid) {
  }
	//根据UID给玩家发消息
	this.sendByUid = function(uid,notify) {
    if(this.robots[uid]){
        setTimeout((function(fun,uid){
          return function() {
            fun.robots[uid].onMessage(notify)
          }
        })(this,uid),1)
    }else{
      if(this.channel.getMember(uid)){
        var tsid = this.channel.getMember(uid)['sid']
        channelService.pushMessageByUids('onMessage', notify, [{
          uid: uid,
          sid: tsid
        }]);
      }
    }
  }
  //根据椅子号给玩家发信息
  this.sendByChair = function(chair,notify) {
    if(this.players[chair].isActive){
      this.sendByUid(this.players[chair].uid,notify)
    }
  }
	//给房间内所有玩家发消息
  this.sendAll = function(notify) {
  	this.channel.pushMessage('onMessage',notify)
    for(var i = 0;i < this.players.length;i++){
      if(this.players[i].isActive && this.players[i].isRobot){
        setTimeout((function(fun,uid){
          return function() {
            if(fun.robots[uid]){
              fun.robots[uid].onMessage(notify)
            }
          }
        })(this,this.players[i].uid),1)
      }
    }
  }
  this.handle.say = function(uid,sid,param,cb) {
    var chair = this.chairMap[uid]
    if(this.players[chair] && this.players[chair].isActive){
      this.players[chair].say(param.msg)
      cb(true)
    }else{
      cb(false)
    }
  }
  //玩家准备
  this.handle.ready = function(uid,sid,param,cb) {
    var chair = this.chairMap[uid]
    if(chair === undefined){
      cb(false,"不在椅子上")
      return
    }
    //游戏已开始不能准备
    if(this.beginFlag){
      cb(false,"游戏已开始")
      return
    }
    if(this.players[chair].isReady){
      cb(false,"已准备")
      return
    }
    this.players[chair].isReady = true
    var notify = {
      cmd: "userReady",
      uid: uid,
      chair : chair
    }
    this.sendAll(notify)
    cb(true)
    this.checkAllReady()
  }
  //游戏开始判断
  this.checkAllReady = function() {
    if(this.beginFlag){
      return
    }
    var tmpCount = 0
    var allCount = 0
    for(var i in this.players){
      if(this.players[i].isActive){
        allCount++
        if(this.players[i].isReady){
          tmpCount++
        }
      }
    }
    if(tmpCount >= this.max_player || (tmpCount >=  this.min_player && tmpCount == allCount)){
      this.beginFun()
    }
  }
  //开始倒计时检测
  this.checkCountDown = function() {
    //开始倒计时判断
    if(this.beginMode == gameCfg.BEGIN_MODE.COUNT_DOWN || this.beginMode == gameCfg.BEGIN_MODE.AUTO_READY){
      var tmpCount = 0
      for(var i in this.players){
        if(this.players[i].isActive){
          tmpCount++
        }
      }
      if(tmpCount >= this.min_player){
        this.countDownEndTime = (new Date).getTime() + this.countDownTime
        var notify = {
          cmd : "beginCountDown",
          countDownEndTime : this.countDownEndTime
        }
        this.sendAll(notify)
        var cbFun = function(){
          var flag = true
          for(var i in this.players){
            if(this.players[i].isActive && !this.players[i].isReady){
              if(this.beginMode == gameCfg.BEGIN_MODE.COUNT_DOWN){
                this.userQuit(this.players[i].uid)
                flag = false
              }else if(this.beginMode == gameCfg.BEGIN_MODE.AUTO_READY){
                this.players[i].isReady = true
              }
            }
          }
          if(flag){
            this.beginFun()
          }
        }
        clearTimeout(this.beginTimer)
        this.beginTimer = setTimeout(cbFun.bind(this),this.countDownTime)
      }
    }
  }
  /**
   * 遍历活跃的玩家
   * @Author   wfd
   * @DateTime 2018-05-18
   * @param    {[type]}   fun [description]
   * @return   {[type]}       [description]
   */
  this.forEachActive = function(fun) {
    for(var i = 0;i < this.players.length;i++){
      if(this.players[i].isActive){
        fun(this.players[i])
      }
    }
  }
  /**
   * 遍历已准备玩家
   * @Author   wfd
   * @DateTime 2018-05-18
   * @param    {[type]}   fun [description]
   * @return   {[type]}       [description]
   */
  this.forEachReady = function(fun) {
    for(var i = 0;i < this.players.length;i++){
      if(this.players[i].isActive){
        fun(this.players[i])
      }
    }
  }
  /**
   * 写入分数
   * @Author   wfd
   * @DateTime 2018-06-05
   * @param    {[type]}   uid   [玩家UID]
   * @param    {[type]}   score [分数改变值]
   * @return   {[type]}         [description]
   */
  this.writeScore = function(uid,score) {
    if(uid > 10000){
      GameRemote.app.rpc.db.remote.addItemReason(null,uid,102,score,this.matchType,null)
    }
  }
  //主循环
  this.mainUpdate = function() {
    // body...
  }
}